package com.chongchong.basicdata.controller;

import com.chongchong.basicdata.entity.NoInfo;
import com.chongchong.basicdata.service.INoInfoService;
import com.chongchong.common.cache.CacheNames;
import com.chongchong.common.enums.ApiErrorCode;
import com.chongchong.common.enums.NoTypeEnum;
import com.chongchong.common.tool.CommonUtil;
import com.chongchong.core.tool.api.R;
import com.chongchong.core.tool.utils.DateUtil;
import com.chongchong.core.tool.utils.RedisUtil;

import com.chongchong.core.tool.utils.StringUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * <h4>springcloud-activiti7</h4>
 * <p></p>
 *
 * @author : tlp
 * @date : 2022-08-11 10:32
 **/
@RestController
@AllArgsConstructor
@RequestMapping("/basicData")
@Api(value = "基础数据", tags = "基础数据接口")
@Slf4j
public class BasicDataController {

	private INoInfoService noInfoService;

	private RedisUtil redisUtil;

	@GetMapping("/createNo")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "生成编号", notes = "传入noType")
	public R<Object> detail(@RequestParam("noType") Integer noType) {
		log.info("开始生成编号：{}", noType);
		String redisKey = CacheNames.NO_KEY + ":" + NoTypeEnum.getEnum(noType).getNoPrefix() + "_" + DateUtil.format(new Date(), "yyyyMMdd");
		Long seq = redisUtil.incr(redisKey, 1);
		String no = CommonUtil.createNo(noType, String.format("%05d", seq));
		if (StringUtil.isBlank(no)) {
			log.info("生成编号错误：[{}]业务类型不存在", noType);
			return R.fail(ApiErrorCode.NO_NOT_EXIST.getErrMessage());
		}
		NoInfo noInfo = new NoInfo();
		noInfo.setNoType(noType);
		noInfo.setNo(no);
		noInfo.setCreateTime(new Date());
		noInfoService.save(noInfo);
		log.info("生成编号成功：{}", no);
		return R.data(no);
	}

	@GetMapping("/createAccount")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "生成account", notes = "传入noType和code")
	public R<Object> createAccount(@RequestParam("noType") Integer noType,@RequestParam("code") String code) {
		log.info("开始生成account：{}", noType,code);
		String no = NoTypeEnum.getEnum(noType).getNoPrefix()+"_"+(StringUtil.hasText(code)?code:CommonUtil.createRandom(8))+"_"+CommonUtil.createRandom(4);
		if (StringUtil.isBlank(no)) {
			log.info("生成account错误：[{}]业务类型不存在", noType);
			return R.fail(ApiErrorCode.NO_NOT_EXIST.getErrMessage());
		}
		NoInfo noInfo = new NoInfo();
		noInfo.setNoType(noType);
		noInfo.setNo(no);
		noInfo.setCreateTime(new Date());
		noInfoService.save(noInfo);
		log.info("生成account成功：{}", no);
		return R.data(no);
	}

}
